﻿<%@ Control Language="C#" AutoEventWireup="true" Inherits="App_Code.Modules.BookModule" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Import Namespace="Portal.Data.Entity" %>

<div id="listbook">
    <style>
        .title{margin-top: -30px;margin-left: -4px;}
        .undertitle{position: absolute;right: 0;top: 25%;}
        td.crawler {position: relative;height: 60px;}
        td.crawler .click {position: absolute;bottom: 3px;right: 3px;padding: 0 3px;background-color: #ccc;text-align: center;cursor: pointer;}
        td .onbottom {position: absolute;bottom: 3px;left: 3px;padding: 0 3px;}
        td.crawler .ontop {position: absolute;top: 0;right: 3px;padding: 0 3px;text-align: center;}
        td.crawler .ontop span {background-color: #ccc;color: blue;}

        td.crawler ul {margin: 0;padding: 0;}
        td.crawler ul li {list-style-image: none;float: left;width: 15%;margin-right: 2%;}
        .true a {color: green !important;}
        .false a {color: red !important;}
        a.maintitle {color: red;}
        p, p a {font-size: 10px !important;}
        .CommandRemake {display: none;}
        .change {font-size: 95% !important;position: absolute;bottom: 0;color: #999!important;right: 10px;}
        .AlterItem td, .Item td {/*height: 80px;*/}
    </style>
    <div class="Header" onclick="toggle(filter);">
        Ẩn/ Hiện bộ lọc
    </div>
    <fieldset style="margin-bottom: 20px; background-color: #f4f4f4" id="filter">
        <legend>Lọc </legend>
        <br />
        <asp:Panel runat="server" ID="pn1" DefaultButton="btnSearch">
            <div style="width: 100%">
                <table class="customlist" cellpadding="0" cellspacing="0" style="float: left; width: 99%;">
                    <tr>
                        <td colspan="10">Theo từ khóa
                        <br />
                            <asp:TextBox ID="Key" runat="server" Width="400"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td style="width: 200px;">Theo thể loại
                        <br />
                            <asp:DropDownList Width="95%" ID="cboType" runat="server" DataValueField="ID" DataTextField="FullName">
                            </asp:DropDownList>
                        </td>
                        <td style="width: 80px;">Xuất bản?
                        <br />
                            <asp:DropDownList Width="95%" ID="cboStatus" runat="server">
                                <asp:ListItem Selected="True" Text="------" Value="-1" />
                                <asp:ListItem Text="Yes" Value="1" />
                                <asp:ListItem Text="No" Value="0" />
                            </asp:DropDownList>
                        </td>
                        <td style="width: 80px;">Kết thúc?
                        <br />
                            <asp:DropDownList Width="95%" ID="cboFinish" runat="server">
                                <asp:ListItem Selected="True" Text="------" Value="-1" />
                                <asp:ListItem Text="Yes" Value="1" />
                                <asp:ListItem Text="No" Value="0" />
                            </asp:DropDownList>
                        </td>
                        <td style="width: 80px;">Hot?
                        <br />
                            <asp:DropDownList Width="95%" ID="cboHot" runat="server">
                                <asp:ListItem Selected="True" Text="------" Value="-1" />
                                <asp:ListItem Text="Yes" Value="1" />
                                <asp:ListItem Text="No" Value="0" />
                            </asp:DropDownList>
                        </td>
                        <td style="width: 80px;">Duy nhất?
                        <br />
                            <asp:DropDownList Width="95%" ID="cboUniquee" runat="server">
                                <asp:ListItem Selected="True" Text="------" Value="-1" />
                                <asp:ListItem Text="Yes" Value="1" />
                                <asp:ListItem Text="No" Value="0" />
                            </asp:DropDownList>
                        </td>
                        <td style="width: 120px;">Nguồn crawl
                        <br />
                            <asp:DropDownList ID="cboCrawlHost" runat="server" Width="95%">
                                <asp:ListItem Selected="True" Text="------" Value="" />
                                <asp:ListItem Text="TruyenGi" Value="truyengi" />
                                <asp:ListItem Text="Blog Truyện" Value="blogtruyen" />
                                <asp:ListItem Text="Comic VN" Value="comicvn" />
                                <asp:ListItem Text="Vitaku" Value="vitaku" />
                            </asp:DropDownList>
                        </td>
                        <td>Theo tác giả
                        <br />
                            <asp:DropDownList ID="cboAuthor" runat="server" DataValueField="ID" DataTextField="FullName" Width="95%">
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td style="width: 200px;">Sắp xếp theo
                        <br />
                            <asp:DropDownList ID="cboOrderBy" runat="server" Width="95%">
                                <Items>
                                    <asp:ListItem>FullName</asp:ListItem>
                                    <asp:ListItem>Visited</asp:ListItem>
                                    <asp:ListItem>RateAverage</asp:ListItem>
                                    <asp:ListItem>CreatedDate</asp:ListItem>
                                    <asp:ListItem Selected="True">ModifiedDate</asp:ListItem>
                                </Items>
                            </asp:DropDownList>
                        </td>
                        <td>
                            <br />
                            <asp:DropDownList ID="cboOrderAct" runat="server" Width="95%">
                                <Items>
                                    <asp:ListItem>Asc</asp:ListItem>
                                    <asp:ListItem Selected="True">Desc</asp:ListItem>
                                </Items>
                            </asp:DropDownList>
                        </td>
                        <td colspan="5"></td>
                    </tr>
                    <tr>
                        <td colspan="6">
                            <asp:Button ID="btnSearch" Width="100" runat="server" Text="Lọc" OnClick="OnSearch" />
                        </td>
                        <td colspan="2" style="text-align: right">
                            <input type="text" id="txtid" placeholder="Xem nhanh theo mã Id" style="width: 153px" />
                            <input type="button" value=" Auto Crawler Updated " onclick="openAutoCrawler($('#txtid').val())"/>
                            <input type="button" id="btnGoId" value=" Đến " />
                        </td>
                    </tr>
                </table>
            </div>

        </asp:Panel>
    </fieldset>
    <asp:Button ID="New" runat="server" OnClick="New_Click" Text="Tạo mới" />
    <br />

    <asp:PlaceHolder runat="server" ID="phPagingTop"></asp:PlaceHolder>
    <br class="clear" />
    <br class="clear" />
    <asp:Repeater ID="Books" runat="server" OnItemCommand="Books_ItemCommand">
        <HeaderTemplate>
            <table class="Contents" cellpadding="0" cellspacing="0">
                <tr class="Header" style="font-size: 13px;">
                    <td style="width: 30px">Id
                    </td>
                    <td style="width: 50px">Cover
                    </td>
                    <td style="min-width: 270px">Title
                    </td>
                    <td style="width: 150px">Thể loại
                    </td>
                    <td style="width: 100px"></td>
                    <td style="min-width: 140px">Info
                    </td>
                    <td style="width: 20px"></td>
                    <td style="width: 20px"></td>
                </tr>
        </HeaderTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
        <AlternatingItemTemplate>
            <tr class="AlterItem">
                <td>
                    <%#Eval("Id")%>
                </td>
                <td style="position: relative">
                    <div style='overflow: hidden; height: 50px; margin-top: -10px;' id="thumb<%#Eval("Id")%>">
                        <%#Book.RenderImage((string)Eval("Image"),50,"",false) %>
                    </div>
                    <a class="change" href="javascript:openBookUpload('<%#Eval("Id")%>');" title="Bấm để thay đổi">###
                    </a>
                </td>
                <td class="crawler">
                    <div class='title'><%#GetDisplayTitle(Eval("FullName"), (bool)Eval("Status"), Eval("URL"))%></div>
                    <p class="undertitle">						
						<%#Eval("SortName")%>
						&nbsp;|&nbsp;
						<span>
							<%#GenAuthor(Eval("AuthorId"),(string)Eval("CrawlAuthor"))%>
						</span>
					</p>
                    <div title='Xem nội dung trang gốc' class='click' onclick="window.open('<%#Eval("CrawlUrl") %>','_blank');">+</div>
                   
                    <div class="onbottom">
                        <a href="javascript:loadChaps('<%#Eval("Id")%>');">Danh sách</a>
                        &nbsp;|&nbsp;<a href="/Admin_Content_content__new.aspx?bid=<%#Eval("Id")%>">Thêm chương</a>
                        &nbsp;|&nbsp;<a href="javascript:openAutoCrawler('<%#Eval("Id")%>')">Auto Crawl</a>
                    </div>
                </td>
                <td style="position: relative; vertical-align: top;">
                    <div id="category<%#Eval("Id")%>">
                        <%#GetHistoryTypeName(Eval("HistoryTypeIds"))%>
                    </div>
                    <a class="change" href="javascript:openBookType('<%#Eval("Id")%>');" title="Bấm để thay đổi">###
                    </a>
                </td>
                <td>
                    <%# Eval("Visited") %> view<br/>
                    <span id='totalchap_<%#Eval("Id")%>'><%# Eval("TotalChap") %></span> chaps<br/>
                    <%# Eval("RateAverage") %>/<%# Eval("RateTotal") %> rating
                </td>
                <td nowrap style="font-size: 11px;" class="crawler">
                    <ul>
                        <li>Finish<br />
                            <b><a title="Click to switch!" id='sf<%# Eval("Id")%>' href="javascript:switchFinish('<%# Eval("Id")%>');"><%# Eval("Finish")%></a></b>
						</li>
                        <li>Status<br />
                            <b><a title="Click to switch!" id='ss<%# Eval("Id")%>' href="javascript:switchStatus('<%# Eval("Id")%>');"><%# Eval("Status")%></a></b></li>
                        <li>Uniq<br />
                            <b><a title="Click to switch!" id='su<%# Eval("Id")%>' href="javascript:switchUniquee('<%# Eval("Id")%>');"><%# Eval("IsUnique")%></a></b></li>
                        <li>HOT<br />
                            <b><a title="Click to switch!" id='sh<%# Eval("Id")%>' href="javascript:switchHot('<%# Eval("Id")%>');"><%# Eval("IsHot")%></a></b></li>
                    </ul>
                    <i class="click">
                        <%# Eval("CrawlHost")%></i>
                    <div class="ontop">
                        update: <span><%# ((DateTime) Eval("ModifiedDate")).ToString("dd/MM/yyyy HH:mm")%></span>
                    </div>
                </td>
                <td style="padding-left: 10px; white-space: nowrap">
                    <asp:Button runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" CssClass="CommandEdit"
                        CommandArgument='<%#Eval("ID")%>' />
                    <input type="button" class="CommandRemake" title="Remake file chapter listing" onclick="js:reCreateChapterList('<%#Eval("ID")%>    ');" />
                </td>
                <td style="padding-left: 10px;">
                    <asp:Button runat="server" ID="btnDelete" Text="Delete" CommandName="Delete" CssClass="CommandDelete"
                        ToolTip="Cho vào thùng rác" OnClientClick="return confirmDelete();" CommandArgument='<%#Eval("ID")%>' />
                </td>
            </tr>
        </AlternatingItemTemplate>
        <ItemTemplate>
            <tr class="Item">
                <td>
                    <%#Eval("Id")%>
                </td>
                <td style="position: relative">
                    <div style='overflow: hidden; height: 50px; margin-top: -10px;' id='thumb<%#Eval("Id")%>'>
                        <%#Book.RenderImage((string)Eval("Image"),50,"",false) %>
                    </div>
                    <a class="change" href="javascript:openBookUpload('<%#Eval("Id")%>');" title="Bấm để thay đổi">###
                    </a>
                </td>
                <td class="crawler">
                    <div class='title'><%#GetDisplayTitle(Eval("FullName"), (bool)Eval("Status"), Eval("URL"))%></div>
                    <p class="undertitle">
						<%#Eval("SortName")%>
						&nbsp;|&nbsp;
						<span>
							<%#GenAuthor(Eval("AuthorId"),(string)Eval("CrawlAuthor"))%>
						</span>
					</p>
                   <div title='Xem nội dung trang gốc' class='click' onclick="window.open('<%#Eval("CrawlUrl") %>','_blank');">+</div>
                    <div class="onbottom">
                        <a href="javascript:loadChaps('<%#Eval("Id")%>');">Danh sách</a>
                        &nbsp;|&nbsp;<a href="/Admin_Content_content__new.aspx?bid=<%#Eval("Id")%>">Thêm chương</a>
                        &nbsp;|&nbsp;<a href="javascript:openAutoCrawler('<%#Eval("Id")%>')">Auto Crawl</a>
                    </div>
                </td>
                <td style="position: relative; vertical-align: top;">
                    <div id='category<%#Eval("Id")%>'>
                       <%#GetHistoryTypeName(Eval("HistoryTypeIds"))%>
                    </div>
                    <a class="change" href="javascript:openBookType('<%#Eval("Id")%>');" title="Bấm để thay đổi">###
                    </a>
                </td>
                <td>
                    <%# Eval("Visited") %> view<br/>
                    <span id='totalchap_<%#Eval("Id")%>'><%# Eval("TotalChap") %></span> chaps<br/>
                    <%# Eval("RateAverage") %>/<%# Eval("RateTotal") %> rating
                </td>
                <td nowrap style="font-size: 10px;" class="crawler">
                    <ul>
                        <li>Finish<br />
                            <b><a title="Click to switch!" id='sf<%# Eval("Id")%>' href="javascript:switchFinish('<%# Eval("Id")%>');"><%# Eval("Finish")%></a></b></li>
                        <li>Status<br />
                            <b><a title="Click to switch!" id='ss<%# Eval("Id")%>' href="javascript:switchStatus('<%# Eval("Id")%>');"><%# Eval("Status")%></a></b></li>
                        <li>Uniq<br />
                            <b><a title="Click to switch!" id='su<%# Eval("Id")%>' href="javascript:switchUniquee('<%# Eval("Id")%>');"><%# Eval("IsUnique")%></a></b></li>
                        <li>HOT<br />
                            <b><a title="Click to switch!" id='sh<%# Eval("Id")%>' href="javascript:switchHot('<%# Eval("Id")%>');"><%# Eval("IsHot")%></a></b></li>
                    </ul>
                    <i class="click"><%# Eval("CrawlHost")%></i>
                    <div class="ontop">
                        update: <span><%# ((DateTime) Eval("ModifiedDate")).ToString("dd/MM/yyyy HH:mm")%></span>
                    </div>
                </td>
                <td style="padding-left: 10px; white-space: nowrap">
                    <asp:Button runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" CssClass="CommandEdit"
                        CommandArgument='<%#Eval("ID")%>' />
                    <input type="button" class="CommandRemake" title="Remake file chapter listing" onclick="js:reCreateChapterList('<%#Eval("ID")%>    ');" />
                </td>
                <td style="padding-left: 10px;">
                    <asp:Button runat="server" ID="btnDelete" Text="Delete" CommandName="Delete" CssClass="CommandDelete"
                        ToolTip="Cho vào thùng rác" OnClientClick="return confirmDelete();" CommandArgument='<%#Eval("ID")%>' />
                </td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
    <br class="clear" />
    <br class="clear" />
    <asp:PlaceHolder runat="server" ID="phPagingBottom"></asp:PlaceHolder>
    <div class="mybr">
    </div>
</div>
<div class="hide" id="popupAuToCrawl" title="Tự động lấy chương mới">
    <h2>Book [<span id="displayBookId"></span>]</h2>
    <div id="popupAuToCrawlMessage"></div>
    <p style="text-align: center;padding: 10px 0;">
        <input type="hidden" id="popupAuToCrawlHide"/>
        <input type="button" value="Bắt đầu" id="popupAuToCrawlStart" onclick="autoCrawlStart();"/>
        <input type="button" value="Đóng lại" onclick="js:$('#popupAuToCrawl').dialog('close');"/>
    </p>
</div>

<div id="bookchaps" style="margin-top: 50px;"></div>
<div>
    <telerik:RadWindowManager ID="RadWindowManager1" ShowContentDuringLoad="false" VisibleStatusbar="false"
        ReloadOnShow="true" runat="server" EnableShadow="true">
        <Windows>
            <telerik:RadWindow ID="RadBookUpload" runat="server" Behaviors="Move,Close,Resize" OnClientClose="onBookUploadClose" Width="600" Height="450" Modal="True">
            </telerik:RadWindow>
            <telerik:RadWindow ID="RadBookType" runat="server" Behaviors="Move,Close,Resize" OnClientClose="onBookTypeClose" Width="600" Height="500" Modal="True">
            </telerik:RadWindow>
        </Windows>
    </telerik:RadWindowManager>
    <script type="text/javascript">
        function openBookUpload(bid) {
            var oWnd = radopen("/ajax/UserControl/BookUpload.aspx?bid=" + bid, "RadBookUpload");
            oWnd.show();
        }
        function onBookUploadClose(oWnd) {
            var arg = oWnd.argument;
            if (arg) {                
                arg = arg.toString().trim();    //format: ID|path
                console.log(arg);
                var arr = arg.split('|');
                if(arr.length>=2) {
                    jQuery('#thumb' + arr[0]).html("<img src='" + arr[1] + "'/>");
                }
                oWnd.argument = null;
            }
        }
        
        function openBookType(bid) {
            var oWnd = radopen("/ajax/UserControl/BookType.aspx?bid=" + bid, "RadBookType");
            oWnd.show();
        }
        function onBookTypeClose(oWnd) {
            var arg = oWnd.argument;
            if (arg) {                
                arg = arg.toString().trim();    //format: ID|listselected html
                console.log(arg);
                var arr = arg.split('|');
                if(arr.length>=2) {
                    jQuery('#category' + arr[0]).html(arr[1]);
                }
                oWnd.argument = null;
            }
        }
    </script>
</div>
<br class="clear" />
<script type="text/javascript">    
    jQuery(function($) {
        
        $('#txtid').keyup(function (e) {
            if (e.keyCode == 13) {
                goBook();
            }
        });
        $('#btnGoId').click(function() {
            goBook();
        });

        function goBook() {
            var val = $('#txtid').val();
            if (val.length == 0) {
                $('#txtid').focus();
                alert("Hãy điền mã để xem nhanh!");
            } else window.location.href = "/Admin_Book_Book_lists_edit.aspx?id=" + val;
        }
        
        //process color LI
        $(".crawler ul li").each(function(t) {
            if ($(this).html().indexOf('True') >0) {
                $(this).removeClass('false').addClass('true');
            } else {
                $(this).removeClass('true').addClass('false');
            }
        });
    });
    function loadChaps(bid) {
        jQuery('#bookchaps').html('');
        jQuery("body").animate({ scrollTop: jQuery('#listbook').height()+150}, 500);
        goPageBookAdmin(bid, 0, '#bookchaps');
    }
    function reCreateChapterList(bid) {
        loading(true);
        jQuery.ajax({
            url: '/Ajax.aspx',
            dataType: 'json',
            data: {
                p: 'Book',
                act: 'remakechaplist',
                bid: bid
            },
            success: function () {
                loading(false);
                alert("Success!");
            },
            error: function () { loading(false); }
        });
    }

    function switchStatus(bid) {
        switchFunct('Status',bid,'ss');
    }
    
    function switchUniquee(bid) {       
        switchFunct('Uniquee',bid,'su');
    }
    function switchFinish(bid) {       
        switchFunct('Finish',bid,'sf');
    }
    function switchHot(bid) {
        switchFunct('Hot',bid,'sh');
    }

    function switchFunct(act,bid,prefix) {
        jQuery.ajax({
            url: '/Ajax.aspx',
            data: {
                p: 'Book',
                act: 'switch'+act,
                bid: bid
            },
            success: function (data) {
                jQuery('#'+prefix+bid).html(data);
                var li = jQuery('#' + prefix + bid).parent().parent();
                if(data=="False")
                    li.removeClass("true").addClass("false");
                else
                    li.removeClass("false").addClass("true");
            }
        });
    }
    
    var t = '#popupAuToCrawlMessage';
    function openAutoCrawler(bid) {
        $('#popupAuToCrawlHide').val(bid);
        $('#displayBookId').html(bid);
        $(t).html('');
        jQuery('#popupAuToCrawl').dialog({
            modal: !0,
            minWidth: 500,
            minHeight: 200,
            dialogClass: "",
            show: "fadeIn"
        });
    }

    function autoCrawlStart() {        
        var bid = $('#popupAuToCrawlHide').val();
        
        if(bid.length==0) {
            $(t).html("Hãy chọn sách!");
            return;
        }
        loading(true,t);
        switchButton();
        $.ajax({
            url: "/Ajax.aspx",
            data: {p: "Content",act: "autoCrawl",bid: bid},
            dataType: "json",
            success: function (e) {
                loading(false, t);
                if(e.total==0) {
                    $(t).html("<p>Không có chương mới</p>"+e.msg);
                }
                else {
                    var oldTotal = parseInt($('#totalchap_' + bid).text().trim());
                    $('#totalchap_' + bid).html("<b style='color:green'>"+(oldTotal+e.total)+"</b>");
                    $(t).html("<p>Số chương mới: "+e.total+"</p>"+e.msg);
                }               
                switchButton();
            },
            error: function (e) {
                loading(false, t);
                $(t).html(e);
                switchButton();
            }             
        });
    }

    function switchButton() {
        var dis = $('#popupAuToCrawlStart').attr('disabled');
        if(dis=="disabled")
            $('#popupAuToCrawlStart').removeAttr('disabled');
        else
            $('#popupAuToCrawlStart').attr('disabled','disabled');
    }
</script>

<script runat="server">
   
    protected override string Action
    {
        get { return "lists"; }
    }
    private const int PageSize = 20;
    public string ShowBtnDelete = "true";
    public bool ListByPublish;
    public Book Book;
    protected override void OnLoad(EventArgs e)
    {
        if (!IsPostBack)
        {
            //load Author
            var authors = new ArrayList
                              {
                                  new Author {ID = -1, FullName = "-All-"},
                                  new Author {ID = 0, FullName = "[Chưa có tác giả]"}
                              };
            authors.AddRange(Author.ListAll());
            cboAuthor.DataSource = authors;
            cboAuthor.DataBind();
            
            //load the loai truyen
            cboType.DataSource = HistoryType.ListAll();
            cboType.DataBind();
            cboType.Items.Insert(0, new ListItem("-All-", "0"));
            try
            {
                if (!string.IsNullOrEmpty(Request["crawlhost"]))
                    cboCrawlHost.SelectedValue = Request["crawlhost"];

                if (!string.IsNullOrEmpty(Request["status"]))
                    cboStatus.SelectedValue = Request["status"];

                if (!string.IsNullOrEmpty(Request["finish"]))
                    cboFinish.SelectedValue = Request["finish"];

                if (!string.IsNullOrEmpty(Request["hot"]))
                    cboHot.SelectedValue = Request["hot"];

                if (!string.IsNullOrEmpty(Request["uniq"]))
                    cboUniquee.SelectedValue = Request["uniq"];

                if (!string.IsNullOrEmpty(Request["auth"]))
                    cboAuthor.SelectedValue = Request["auth"];

                if (!string.IsNullOrEmpty(Request["key"]))
                    Key.Text = Request["key"];

                if (!string.IsNullOrEmpty(Request["orderby"]))
                    cboOrderBy.SelectedValue = Request["orderby"];

                if (!string.IsNullOrEmpty(Request["orderact"]))
                    cboOrderAct.SelectedValue = Request["orderact"];
            }
            catch
            {
            }
            if (Request["forward"] != null)
                BindData();
        }
    }

    private void BindData()
    {
        int count;
        var objSearch = new BookSearchObject { Key = Key.Text };
        if (cboType.SelectedIndex > 0)
            objSearch.BookTypeId = Convert.ToInt32(cboType.SelectedValue);
        
        if (cboCrawlHost.SelectedIndex > 0)
        {
            objSearch.CrawlHost = cboCrawlHost.SelectedValue;
        }
        if (cboStatus.SelectedIndex > 0)
        {
            objSearch.Status = Convert.ToInt32(cboStatus.SelectedValue);
        }
        if (cboFinish.SelectedIndex > 0)
        {
            objSearch.FindFinish = Convert.ToInt32(cboFinish.SelectedValue);
        }
        if (cboHot.SelectedIndex > 0)
        {
            objSearch.FindHot = Convert.ToInt32(cboHot.SelectedValue);
        }
        if (cboUniquee.SelectedIndex > 0)
        {
            objSearch.FindUniquee = Convert.ToInt32(cboUniquee.SelectedValue);
        }
        if (cboAuthor.SelectedIndex >= 0)
        {
            objSearch.Author = Convert.ToInt32(cboAuthor.SelectedValue);
        }
        objSearch.OrderByFieldName = cboOrderBy.SelectedValue;
        objSearch.OrderByAct = cboOrderAct.SelectedValue;
        
        var list = Book.Search(objSearch, PageSize, GetCurrentPage(), out count);

        Books.DataSource = list;
        Books.DataBind();

        AddPagingTool(new Control[] { phPagingTop, phPagingBottom }, count, PageSize, null);
    }

    protected void OnSearch(object sender, EventArgs e)
    {
        if (Key.Text.Length > 0)
            ActionPage.newParams.Add("key", Key.Text.Trim());
        else
            ActionPage.removeQueueParams.Add("key");
        ActionPage.removeQueueParams.Add("page");
        ActionPage.newParams.Add("type", cboType.SelectedValue);
        if (cboCrawlHost.SelectedIndex > 0)
            ActionPage.newParams.Add("crawlhost", cboCrawlHost.SelectedValue);
        else ActionPage.removeQueueParams.Add("crawlhost");

        if (cboStatus.SelectedIndex > 0) ActionPage.newParams.Add("status", cboStatus.SelectedValue);
        else ActionPage.removeQueueParams.Add("status");

        if (cboFinish.SelectedIndex > 0) ActionPage.newParams.Add("finish", cboFinish.SelectedValue);
        else ActionPage.removeQueueParams.Add("finish");
        if (cboHot.SelectedIndex > 0) ActionPage.newParams.Add("hot", cboHot.SelectedValue);
        else ActionPage.removeQueueParams.Add("hot");
        if (cboUniquee.SelectedIndex > 0) ActionPage.newParams.Add("uniq", cboUniquee.SelectedValue);
        else ActionPage.removeQueueParams.Add("uniq");
        if (cboAuthor.SelectedIndex > 0) ActionPage.newParams.Add("auth", cboAuthor.SelectedValue);
        else ActionPage.removeQueueParams.Add("auth");
        ActionPage.newParams.Add("orderby", cboOrderBy.SelectedValue);
        ActionPage.newParams.Add("orderact", cboOrderAct.SelectedValue);
        Forward("search");
    }

    protected void Books_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int id = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName == "Delete")
        {
            (Book.FindByPrimaryKey(id)).Delete();
            Forward("delete");
        }
        else if (e.CommandName == "Edit")
        {
            ActionPage.newParams.Add("id", id);
            Forward("edit");
        }
    }
    protected string GetUser(object eval)
    {
        PortalUser user = PortalUser.FindByPrimaryKey(eval);
        return (user != null) ? user.Name : "";
    }

    protected string GetHistoryTypeName(object typeIds)
    {
        if (typeIds == null) return "";

        var arrIds = typeIds.ToString().Split(',').Select(x => Convert.ToInt32(x));
        var results = HistoryType.ListAll().Where(x => arrIds.Contains(x.ID)).ToList();
        var s = results.Aggregate("", (current, ht) => current + string.Format("<a href='{0}' class='booktype'>{1}</a>, ", ht.Url, ht.FullName));
        return string.IsNullOrEmpty(s) ? "" : s.Remove(s.Length - 2);
    }

    protected string GetDisplayTitle(object title, bool status, object url)
    {
        var path = (status)
                       ? string.Format("<a class='maintitle' href='{0}' target=_blank>{1}</a>", url, title)
                       : title;
        return path.ToString();
    }

    public string GenAuthor(object authorId, string crawlAuthor)
    {
        var aut = Author.FindByPrimaryKey(authorId);
        if (aut != null)
        {
            return string.Format("<a target=_blank href='{0}'>{1}</a>", aut.Url, aut.FullName);
        }
        return crawlAuthor;
    }    
</script>
